Page({
  data: {
    // 城市信息
    city: '110101',
    // 当前天气信息
    currentWeather: {
      temperature: '26°C',
      weather: '晴',
      humidity: '40%',
      wind: '东北风 3级',
      airQuality: '优 72',
      updateTime: '10:30 更新'
    },
    // 天气预报列表
    forecastList: [
      { day: '今天', date: '3/18', weather: '晴', high: '28°C', low: '16°C', icon: 'sunny' },
      { day: '明天', date: '3/19', weather: '多云', high: '26°C', low: '15°C', icon: 'cloudy' },
      { day: '周三', date: '3/20', weather: '小雨', high: '24°C', low: '14°C', icon: 'light-rain' }
    ],
    // 完整天气预报列表（广告后显示）
    fullForecastList: [
      { day: '今天', date: '3/18', weather: '晴', high: '28°C', low: '16°C', icon: 'sunny' },
      { day: '明天', date: '3/19', weather: '多云', high: '26°C', low: '15°C', icon: 'cloudy' },
      { day: '周三', date: '3/20', weather: '小雨', high: '24°C', low: '14°C', icon: 'light-rain' },
      { day: '周四', date: '3/21', weather: '阵雨', high: '22°C', low: '13°C', icon: 'shower' },
      { day: '周五', date: '3/22', weather: '多云', high: '25°C', low: '14°C', icon: 'cloudy' },
      { day: '周六', date: '3/23', weather: '晴', high: '27°C', low: '15°C', icon: 'sunny' },
      { day: '周日', date: '3/24', weather: '晴', high: '29°C', low: '17°C', icon: 'sunny' }
    ],
    // 是否显示完整预报
    showFullForecast: false,
    // 生活指数
    lifeIndex: [
      { name: '紫外线', value: '中等', icon: 'uv' },
      { name: '穿衣', value: '舒适', icon: 'clothing' },
      { name: '洗车', value: '适宜', icon: 'car-wash' },
      { name: '运动', value: '适宜', icon: 'sport' }
    ],
    // 广告相关
    adUnitId: 'txuko51m55q68jkleu', // 替换为您的广告单元ID
    rewardedVideoAd: null,
    isLoading: false
  },

  onLoad: function () {
    // 页面加载时获取天气数据
    this.getWeatherData();

    // 初始化激励视频广告
    this.initRewardedVideoAd();
  },

  // 获取天气数据（模拟）
  getWeatherData: function () {
    // 实际应用中，这里应该调用天气API获取数据
    // 这里使用模拟数据
    tt.showLoading({
      title: '加载中...'
    });

    setTimeout(() => {
      const apiKey = "49555c23c089363d0ea2751bba7c669b"; // 替换成你的 API Key
      const city = this.data.city;

      tt.request({
        url: `https://restapi.amap.com/v3/weather/weatherInfo?city=${city}&key=${apiKey}`,
        method: "GET",
        success: (res) => {
          if (res.data && res.data.status === 0) {
            this.setData({
              weatherInfo: res.data.result,
            });
          } else {
            tt.showToast({
              title: "获取天气失败",
              icon: "none",
            });
          }
        },
        fail: (err) => {
          console.error("请求失败：", err);
          tt.showToast({
            title: "网络错误",
            icon: "none",
          });
        },
      });
      tt.hideLoading();
      // 数据已在data中初始化
    }, 1000);
  },

  // 初始化激励视频广告
  initRewardedVideoAd: function () {
    // 创建激励视频广告实例
    if (tt.createRewardedVideoAd) {
      this.data.rewardedVideoAd = tt.createRewardedVideoAd({
        adUnitId: this.data.adUnitId
      });

      // 监听加载事件
      this.data.rewardedVideoAd.onLoad(() => {
        console.log('激励视频广告加载成功');
      });

      // 监听错误事件
      this.data.rewardedVideoAd.onError((err) => {
        console.log('激励视频广告加载失败', err);
      });

      // 监听关闭事件
      this.data.rewardedVideoAd.onClose((res) => {
        // 用户点击了【关闭广告】按钮
        if (res && res.isEnded) {
          // 正常播放结束，可以下发游戏奖励
          this.showFullWeatherForecast();
        } else {
          // 播放中途退出，不下发游戏奖励
          tt.showToast({
            title: '需要完整观看广告才能查看更多天气信息',
            icon: 'none'
          });
        }
      });
    }
  },

  // 显示激励视频广告
  showRewardedVideoAd: function () {
    if (this.data.rewardedVideoAd) {
      this.setData({
        isLoading: true
      });

      this.data.rewardedVideoAd.show()
        .then(() => {
          this.setData({
            isLoading: false
          });
        })
        .catch(err => {
          this.setData({
            isLoading: false
          });

          // 重新加载广告
          this.data.rewardedVideoAd.load()
            .then(() => this.data.rewardedVideoAd.show())
            .catch(err => {
              tt.showToast({
                title: '广告加载失败，请稍后再试',
                icon: 'none'
              });
              console.log('激励视频广告显示失败', err);
            });
        });
    } else {
      tt.showToast({
        title: '广告组件不存在',
        icon: 'none'
      });
    }
  },

  // 显示完整天气预报
  showFullWeatherForecast: function () {
    this.setData({
      showFullForecast: true
    });

    tt.showToast({
      title: '已解锁完整天气预报',
      icon: 'success'
    });
  },

  // 切换城市
  changeCity: function () {
    console.log('changeCity');
    this.setData({
      cityPickerVisible: true,
    });
  },

  // 刷新天气
  refreshWeather: function () {
    this.getWeatherData();
  },
  // 选择城市回调
  handleCitySelected(e) {
    this.setData({
      city: e.detail.city,
      cityPickerVisible: false,
    });
    this.getWeatherData();
  },
  // 查看详细天气
  viewWeatherDetail: function (e) {
    const index = e.currentTarget.dataset.index;
    const forecast = this.data.showFullForecast ?
      this.data.fullForecastList[index] :
      this.data.forecastList[index];

    tt.navigateTo({
      url: `/pages/weather-detail/weather-detail?day=${forecast.day}&weather=${forecast.weather}`
    });
  }
});